package com.jike.noobmoney.mvp.view.activity;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jike.noobmoney.R;
import com.jike.noobmoney.util.Logger;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
//import com.just.agentweb.WebChromeClient;
//import com.just.agentweb.WebViewClient;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;

/**
 * author: xuke.
 * date: 2017/4/28 14:26
 * 所有的前端界面都可以进这个页面,前提是前端页面没有标题栏
 */

public class MyEventTwoActivity extends BaseActivity {

    /**
     * 拍照/选择文件请求码
     */
    private static final int REQ_CAMERA = 1;
    private static final int REQ_CHOOSE = REQ_CAMERA + 1;

    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadMessageArray;
    private static final String PATH = Environment.getExternalStorageDirectory() + "/DCIM";
    private String imageName;

    public static final String BUNDLE_KEY_URL = "MY_EVENT_BUNDLE_KEY_URL";
    public static final String BUNDLE_KEY_TITLE = "BUNDLE_KEY_TITLE";
    @BindView(R.id.view)
    LinearLayout view;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    private String mWebUrl;
    private String mTitle;
    private WebView webView;


    @Override
    protected int layoutResID() {
        return R.layout.activity_my_event_two;
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mWebUrl = intent.getStringExtra(MyEventTwoActivity.BUNDLE_KEY_URL);
            mTitle = intent.getStringExtra(MyEventTwoActivity.BUNDLE_KEY_TITLE);
        }

        if (!TextUtils.isEmpty(mTitle)) {
            tvTitle.setText(mTitle);
        }

        Logger.e("xuke", "mWebUrl=" + mWebUrl);
        AgentWeb mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) view, new LinearLayout.LayoutParams(-1, -1))
                //.useDefaultIndicator(getResources().getColor(R.color.c_main))
                //.useDefaultIndicator()
                .closeIndicator()
                //.setWebChromeClient(mWebChromeClient)
                //.setWebViewClient(mWebViewClient)
                .createAgentWeb()
                .ready()
                .go(mWebUrl);

        webView = mAgentWeb.getWebCreator().getWebView();
        initWebviews();
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

//        // Android  >= 4.1
//        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
//            if (acceptType.equals("image/*")) {
//                if (mUploadMessage != null) {
//                    mUploadMessage.onReceiveValue(null);
//                    return;
//                }
//                mUploadMessage = valueCallback;
//                selectImage();
//            } else {
//                onReceiveValue();
//            }
//        }
//
//        //  Android < 3.0
//        public void openFileChooser(ValueCallback<Uri> valueCallback) {
//            openFileChooser(valueCallback, "image/*");
//        }
//
//        //  Android  >= 3.0
//        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
//            openFileChooser(valueCallback, acceptType, "");
//        }


        // For Android >=3.0
//        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
//            if (acceptType.equals("image/*")) {
//                if (mUploadMessage != null) {
//                    mUploadMessage.onReceiveValue(null);
//                    return;
//                }
//                mUploadMessage = uploadMsg;
//                selectImage();
//            } else {
//                onReceiveValue();
//            }
//        }


        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType) {
            if (acceptType.equals("image/*")) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                    return;
                }
                mUploadMessage = valueCallback;
                selectImage();
            } else {
                onReceiveValue();
            }
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "image/*");
        }

        // For Android  >= 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

        // For Android  >= 5.0
        @Override
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            super.onShowFileChooser(webView,filePathCallback,fileChooserParams);
            if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                    && fileChooserParams.getAcceptTypes().length > 0 && fileChooserParams.getAcceptTypes()[0].equals("image/*")) {
                if (mUploadMessageArray != null) {
                    mUploadMessageArray.onReceiveValue(null);
                }
                mUploadMessageArray = filePathCallback;
                selectImage();
            } else {
                onReceiveValue();
            }
            return true;
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webView.loadUrl(url);
            return true;

        }
    };


    private void initWebviews() {
        webView.setWebChromeClient(mWebChromeClient);
        webView.setWebViewClient(mWebViewClient);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setDomStorageEnabled(true);
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }


    private void selectImage() {
        String[] selectPicTypeStr = {"拍摄", "从相册中选择"};
        new AlertDialog.Builder(this)
                .setOnCancelListener(dialog -> onReceiveValue())
                .setItems(selectPicTypeStr, (dialog, which) -> {
                    switch (which) {
                        // 相机拍摄，此处调用系统相机拍摄图片，开发者可根据实际情况选用系统相机还是自己在这之上封装一层从而符合APP风格
                        case 0:
                            openCamera();
                            break;
                        // 手机相册，此处调用系统相册选择图片，开发者可根据实际情况选用系统相册还是自己在这之上封装一层从而符合APP风格
                        case 1:
                            openAlbum();
                            break;
                        default:
                            break;
                    }

                })
                .show();
    }

    private void openAlbum() {
        if (!hasSDcard()) {
            return;
        } else {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_PICK);
            intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//使用以上这种模式，并添加以上两句
            startActivityForResult(intent, REQ_CHOOSE);
        }
    }

    private void openCamera() {
        if (!hasSDcard()) {
            return;
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageName = System.currentTimeMillis() + ".png";
            File file = new File(PATH);
            if (!file.exists()) {
                file.mkdirs();
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(PATH, imageName)));
            startActivityForResult(intent, REQ_CAMERA);
        }
    }

    private boolean hasSDcard() {
        boolean flag = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (!flag) {
            Toast.makeText(this, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT).show();
            onReceiveValue();
        }
        return flag;
    }

    /**
     * 返回文件选择
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode != RESULT_OK) {
            onReceiveValue();
            return;
        }
        switch (requestCode) {
            case REQ_CAMERA:
                File fileCamera = new File(PATH, imageName);
                handleFile(fileCamera);
                break;
            case REQ_CHOOSE:
                Uri uri = intent.getData();
                String absolutePath = getAbsolutePath(this, uri);
                File fileAlbum = new File(absolutePath);
                handleFile(fileAlbum);
                break;
        }
    }

    private void handleFile(File file) {
        if (file.isFile()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (null == mUploadMessageArray) {
                    return;
                }
                Uri uri = Uri.fromFile(file);
                Uri[] uriArray = new Uri[]{uri};
                mUploadMessageArray.onReceiveValue(uriArray);
                mUploadMessageArray = null;
            } else {
                if (null == mUploadMessage) {
                    return;
                }
                Uri uri = Uri.fromFile(file);
                mUploadMessage.onReceiveValue(uri);
                mUploadMessage = null;
            }
        } else {
            onReceiveValue();
        }

    }

    public String getAbsolutePath(final Context context,
                                  final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(
                            MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private void onReceiveValue() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mUploadMessageArray != null) {
                mUploadMessageArray.onReceiveValue(null);
                mUploadMessageArray = null;
            }
        } else {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
        }
    }


    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AgentWebConfig.clearDiskCache(this);
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        onBackPressed();
    }
}
